<?php
/**
 * A csv file creator
 * @author Bruce Li
 * @interface UI
 */
class csv_upload
{
    /**
     * variables for view
     * @var array
     */
    protected $_vars = array();


    /**
     * run the app
     * @return void
     */
    public function run()
    {
        if (Blib::isPost()) {
            // call the post handler
            $this->_handlePost();
        }

        require_once dirname(__file__) . '/../templates/form.phtml';

    }// end run


    /**
     * the inputs...
     * @param str $name the name
     * @param str $value the default value
     * @param str $id the id
     * @param str $type the type text|pass|file
     * @param str $extra any extra shit to put on it
     * @return void
     */
    public function input($name, $value = '', $id = '', $type = 'text', $extra = '')
    {
        if (empty($value)) {
            $value = $this->get($name);
        }if (empty($id)) {
            $id = $name;
        }
        if ($type == 'file') {
            $value = null;
        }
        if ($type !== 'submit' && $type != 'reset') {
            echo "<label>{$name}</label>";
        }
        if ($type != 'textarea') {
            echo "<input name='{$name}' id='{$id}' type='{$type}' value='{$value}' {$extra} /><br />";
        } else {
            echo "<textarea name='{$name}' id='{$id}' {$extra}>{$value}</textarea><br />";
        }

    }// end input


    /**
     * handle the post
     */
    protected function _handlePost()
    {
        // first of all, register all post values
        $this->_vars = $_POST;
        // check if the necessary ones are there...
        $id       = Blib::getInput('id');
        $name     = Blib::getInput('name');
        $formLink = Blib::getInput('formLink', 'http://racingguide.centrebet.com/formguide.html');
        $expires  = Blib::getInput('expires');
        // validate...
        $isError = false;
        if (empty($id) || empty($name) || empty($expires)) {
            $this->set('error', 'id/name/expires must be filled<br />');
            $isError = true;
        }
        if (empty($_FILES['data']['tmp_name'])) {
            $this->set('error', $this->get('error') . 'Data file must be uploaded.<br />');
            $isError = true;
        }
        $this->set('isError', $isError);

        // do the thingy
        if (!$isError) {
            $result = '// converted data file @' . date('Y-m-d H:i:s') .
                      "\n//\n//  Race info\n//\n" .
                      "var raceData = { \n" .
                      "    'id': '{$id}',\n" .
                      "    'name': '{$name}',\n" .
                      "    'formLink': '{$formLink}',\n" .
                      "    'expires': '{$expires}'\n" .
                      "};\n" .
                      "//\n//  Horse data\n//\n" .
                      "var horseData = {};\n\n";
            // deal with the csv here...
            if (substr($_FILES['data']['name'], -4) !== '.csv') {
                // wrong format!
                $this->set('isError', true);
                $this->set('error', 'File is not valid csv! Must be [text/comma-separated-values]');
                return false;
            }

            // otherwise... do it!
            $data    = (array) @file($_FILES['data']['tmp_name']);
            // now, deal with the mapping
            /*
            Selection ID,Selection ID,Horse,barrier,Country,,,,,,,,,,

            horseData[selection id > 100] = {
            'number':[selection id again],
            'name':[Horse],
            'barrier':[barrier],
            'nationality':[Country],
            'agesx':[age/sex],
            'sire':[sire],
            'dam':[dam],
            'weight':[weight],
            'jockey':[Jockey],
            'trainer':[Trainer],
            'career':[career],
            'last6run':[last 6],
            'prize':[prize money],
            'img_url':[img_url]
            };
             */
            $hdr  = str_getcsv(strtolower($data[0]));
            $hdrs = array();
            // expolde first row to decide which is id...
            $row1  = str_getcsv(strtolower($data[1]));
            $total = count($hdr);
            if (count($row1) !== $total) {
                $this->set('isError', true);
                $this->set('error', 'File may contain extra commas in the actual fields! Clean them up!');
                return false;
            }
            // start mapping
            foreach ($hdr as $k => $pcs) {
                $pcs = trim($pcs);
                switch ($pcs) {
                    case 'selection id':
                        if (trim($row1[$k]) > 100) {
                            $hdrs['selection_id'] = $k;
                        } else {
                            $hdrs['number'] = $k;
                        }
                        break;
                    case 'horse':
                        $hdrs['name'] = $k;
                        break;
                    case 'country':
                        $hdrs['nationality'] = $k;
                        break;
                    case 'age/sex':
                        $hdrs['agesx'] = $k;
                        break;
                    case 'last 6':
                        $hdrs['last6run'] = $k;
                        break;
                    case 'prize money':
                        $hdrs['prize'] = $k;
                        break;
                    default:
                        $hdrs[$pcs] = $k;
                        break;
                }
            }
            // show us!
            // $result .= var_export($hdrs, 1);
            // get rid of hdr for the rest of the rows..
            unset($data[0]);
            foreach ($data as $pcs) {
                $tmpAr = str_getcsv($pcs);
                if (count($tmpAr) !== $total) {
                    $this->set('isError', true);
                    $this->set('error', 'File may contain extra commas in the actual fields! Clean them up!');
                    return false;
                }
                // otherwise, map it and write it...
                $result .= "horseData[" . $tmpAr[$hdrs['selection_id']] . "] = {
	'number':'" . $tmpAr[$hdrs['number']] . "',
	'name':'" . $tmpAr[$hdrs['name']] . "',
	'barrier':'" . $tmpAr[$hdrs['barrier']] . "',
	'nationality':'" . $tmpAr[$hdrs['nationality']] . "',
	'agesx':'" . $tmpAr[$hdrs['agesx']] . "',
	'sire':'" . $tmpAr[$hdrs['sire']] . "',
	'dam':'" . $tmpAr[$hdrs['dam']] . "',
	'weight':'" . $tmpAr[$hdrs['weight']] . "',
	'jockey':'" . $tmpAr[$hdrs['jockey']] . "',
	'trainer':'" . $tmpAr[$hdrs['trainer']] . "',
	'career':'" . $tmpAr[$hdrs['career']] . "',
	'last6run':'" . $tmpAr[$hdrs['last6run']] . "',
	'prize':'" . $tmpAr[$hdrs['prize']] . "',
	'img_url':'" . $tmpAr[$hdrs['img_url']] . "'
};
";
            }


            // do the thingy here...
            $this->set('result', $result . 'var allDataLoaded = true;');
            return true;
        }

    }// end _handlePost


    /**
     * set a var
     * using Blib
     * @param str $key the kye
     * @param mixed $val the value
     * @return void
     */
    public function set($key, $val)
    {
        $this->_vars[$key] = $val;

    }// end set


    /**
     * get view var
     * @param str $key the key
     * @param mixed $default if empty, the default
     * @return mixed
     */
    public function get($key, $default = null)
    {
        if (!empty($this->_vars[$key])) {
            return $this->_vars[$key];
        }

        return $default;

    }// end get

}// end csv_upload
?>